package top.tangyh.lamp.care.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.util.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.tangyh.basic.exception.BizException;
import top.tangyh.lamp.care.mapper.BCarePgVteMapper;
import top.tangyh.lamp.care.service.BCarePgVteService;
import top.tangyh.basic.base.service.impl.SuperServiceImpl;
import top.tangyh.lamp.care.manager.BCarePgVteManager;
import top.tangyh.lamp.care.entity.BCarePgVte;
import top.tangyh.lamp.care.vo.result.Apache2Statstic;
import top.tangyh.lamp.care.vo.result.BCarePgVteResultVO;
import top.tangyh.lamp.care.vo.result.BCarePgVteVO;
import top.tangyh.lamp.care.vo.result.CarePgVteVO;
import top.tangyh.lamp.care.vo.save.BCarePgVteSaveVO;
import top.tangyh.lamp.common.utils.ConvertUtil;
import top.tangyh.lamp.common.utils.ValidationUtil;
import top.tangyh.lamp.common.utils.YDateUtils;

import java.util.*;

/**
 * <p>
 * 业务实现类
 * vte风险评分
 * </p>
 *
 * @author zqb
 * @date 2024-07-08 16:40:03
 * @create [2024-07-08 16:40:03] [zqb] [代码生成器生成]
 */
@Slf4j
@RequiredArgsConstructor
@Service
@Transactional(readOnly = true)
public class BCarePgVteServiceImpl extends SuperServiceImpl<BCarePgVteManager, Long, BCarePgVte> implements BCarePgVteService {

    private final BCarePgVteMapper bCarePgVteMapper;
    @Override
    public void checkPg(BCarePgVteSaveVO yxCarePgVteVO) {
        if(bCarePgVteMapper.checkPg(yxCarePgVteVO.getPatientIdent(),yxCarePgVteVO.getPfTime(),yxCarePgVteVO.getPfr(),yxCarePgVteVO.getType())){
            throw new BizException("此时间点已有该评分");
        }

    }

    @Override
    public BCarePgVte getLastNewCarePgRecord(int type,String dateStr,String patientIdent) {
        QueryWrapper<BCarePgVte> wrapper = new QueryWrapper<>();
        wrapper.eq("type",type);
        wrapper.eq(StringUtil.isNotEmpty(patientIdent),"patient_ident",patientIdent);
        wrapper.eq("is_deleted",0);
        //只展示 来自his的数据
        wrapper.eq("source",1);
        wrapper.apply(StringUtil.isNotEmpty(dateStr),"date_format(pf_time,'%Y-%m-%d') = '" + dateStr+"'");

        wrapper.orderByDesc("pf_time");
        wrapper.last("LIMIT 1");
        // 第二个参数
        // 如果返回的结果集多余一条数据，则抛出如下错误：
        // TooManyResultsException
        BCarePgVte carePgVtePO = bCarePgVteMapper.selectOne(wrapper, true);
        return carePgVtePO;
    }

    @Override
    public BCarePgVte getLastNewCarePgRecord(int type,String patientIdent,Long rkTime,Long ckTime) {
        QueryWrapper<BCarePgVte> wrapper = new QueryWrapper<>();
        wrapper.eq("type",type);
        wrapper.eq(StringUtil.isNotEmpty(patientIdent),"patient_ident",patientIdent);
        wrapper.eq("is_deleted",0);
        if(null != rkTime){
            wrapper.ge("pf_time",new Date(rkTime));
        }
        if(null != ckTime){
            wrapper.le("pf_time",new Date(ckTime));
        }
        wrapper.orderByDesc("pf_time");
        wrapper.last("LIMIT 1");
        // 第二个参数
        // 如果返回的结果集多余一条数据，则抛出如下错误：
        // TooManyResultsException
        BCarePgVte carePgVtePO = bCarePgVteMapper.selectOne(wrapper, true);
        return carePgVtePO;
    }

    @Override
    public BCarePgVte getFirstCarePgRecord(int type,String dateStr,String patientIdent) {
        QueryWrapper<BCarePgVte> wrapper = new QueryWrapper<>();
        wrapper.eq("type",type);
        wrapper.eq(StringUtil.isNotEmpty(patientIdent),"patient_ident",patientIdent);
        wrapper.eq("is_deleted",0);
        if(type == 1){
            wrapper.eq("source",1);
        }
        wrapper.apply(StringUtil.isNotEmpty(dateStr),"date_format(pf_time,'%Y-%m-%d') = '" + dateStr+"'");

        wrapper.orderByAsc("pf_time");
        wrapper.last("LIMIT 1");
        // 第二个参数
        // 如果返回的结果集多余一条数据，则抛出如下错误：
        // TooManyResultsException
        BCarePgVte carePgVtePO = bCarePgVteMapper.selectOne(wrapper, true);
        return carePgVtePO;
    }

    @Override
    public String getVteOfTopNewScore(String patientIdent) {
        String score="";
        BCarePgVteVO yxCarePgVteVO=bCarePgVteMapper.getVteOfTopNew(patientIdent);
        if(null!=yxCarePgVteVO){

            try {
                JSONArray jarr=JSONArray.parseArray(yxCarePgVteVO.getJsonText());//JSON.parseArray(jsonStr);
                //倒序序号 最后的先遍历 最后的代表最新的
                for (int i = jarr.size()-1; i >=0; i--) {
                    JSONObject job=jarr.getJSONObject(i);
                    String allScore1="";
                    String allScore2="";
                    String allScore3="";
                    if(null!=job.get("allScore1")){
                        allScore1= job.get("allScore1").toString();
                    }
                    if(null!=job.get("allScore2")){
                        allScore2= job.get("allScore2").toString();
                    }
                    if(null!=job.get("allScore3")){
                        allScore3= job.get("allScore3").toString();
                    }

                    if(ValidationUtil.isNumeric(allScore3)){
                        score=allScore3;
                        break;
                    }else if(ValidationUtil.isNumeric(allScore2)){
                        score=allScore2;
                        break;
                    }else if(ValidationUtil.isNumeric(allScore1)){
                        score=allScore1;
                        break;
                    }
                }
            }catch (Exception e){
                log.error(e.getMessage());
                return score;
            }

        }

        return score;
    }

    @Override
    public Map<String,String> getVteOfTopNewScoreByList(List<String> patientIdents) {
        Map<String,String> map=new HashMap<>();

        List<BCarePgVteVO> yxCarePgVteVOList=bCarePgVteMapper.getVteOfTopNewByList(patientIdents);
        if(null!=yxCarePgVteVOList&&yxCarePgVteVOList.size()>0){
            for (int j = 0; j <yxCarePgVteVOList.size() ; j++) {
                String score="";
                BCarePgVteVO yxCarePgVteVO=yxCarePgVteVOList.get(j);
                try {
                    JSONArray jarr=JSONArray.parseArray(yxCarePgVteVO.getJsonText());//JSON.parseArray(jsonStr);
                    //倒序序号 最后的先遍历 最后的代表最新的
                    for (int i = jarr.size()-1; i >=0; i--) {
                        JSONObject job=jarr.getJSONObject(i);
                        String allScore1="";
                        String allScore2="";
                        String allScore3="";
                        if(null!=job.get("allScore1")){
                            allScore1= job.get("allScore1").toString();
                        }
                        if(null!=job.get("allScore2")){
                            allScore2= job.get("allScore2").toString();
                        }
                        if(null!=job.get("allScore3")){
                            allScore3= job.get("allScore3").toString();
                        }

                        if(ValidationUtil.isNumeric(allScore3)){
                            score=allScore3;
                            break;
                        }else if(ValidationUtil.isNumeric(allScore2)){
                            score=allScore2;
                            break;
                        }else if(ValidationUtil.isNumeric(allScore1)){
                            score=allScore1;
                            break;
                        }
                        map.put(yxCarePgVteVO.getPatientIdent(),score);
                    }
                }catch (Exception e){
                    log.error(e.getMessage());
                    return map;
                }

            }

        }

        return map;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveList(List<CarePgVteVO> pgs, Long recordTime, String operator, String patientIdent, Set<Integer> pgpfs) {

        Set<String> pfr = new HashSet<>();
        pfr.add(operator);
        Date start = YDateUtils.stringToDate(YDateUtils.format(new Date(recordTime),YDateUtils.DATE_TIME_MINUTE_PATTERN)+":00",YDateUtils.DATE_TIME_PATTERN);
        Date end = YDateUtils.stringToDate(YDateUtils.format(new Date(recordTime),YDateUtils.DATE_TIME_MINUTE_PATTERN)+":59",YDateUtils.DATE_TIME_PATTERN);
        bCarePgVteMapper.deletetOld(patientIdent,start,end,pfr,pgpfs);
        if(CollectionUtil.isEmpty(pgs)){
            return;
        }
        List<BCarePgVte> pos = new ArrayList<>();
        for(CarePgVteVO item : pgs){
            BCarePgVte po = ConvertUtil.convert(item, BCarePgVte.class);
            po.setId(null);
            po.setPfTime(YDateUtils.getDateTimeOfTimestamp(recordTime));
            po.setPfr(operator);
            pos.add(po);
        }
        saveBatch(pos);

    }

    @Override
    public Map<Integer, CarePgVteVO> selectLatestByParams(String patientIdent, String hospitalNumber, Set<Integer> vte, Long recordTime,Long rkTime) {
        Map<Integer, CarePgVteVO> result = new HashMap<>();
        if(CollectionUtil.isEmpty(vte)){
            return result;
        }
        for(Integer type : vte){
            List<BCarePgVte> records = bCarePgVteMapper.selectLatestByParams(patientIdent,hospitalNumber,type,recordTime,rkTime);
            if(CollectionUtil.isNotEmpty(records)){
                result.put(records.get(0).getType(),ConvertUtil.convert(records.get(0),CarePgVteVO.class));
            }
        }

        return result;
    }

    @Override
    public List<BCarePgVteVO> getFirstApacheiiPatients(String startTime, String endTime) {
        return bCarePgVteMapper.getFirstApacheiiPatients(startTime,endTime);
    }

    @Override
    public List<Apache2Statstic> selectApacheIIFirstStatistics(String startTime, String endTime) {
        return bCarePgVteMapper.selectApacheIIFirstStatistics(startTime,endTime);
    }


    public Page<BCarePgVteResultVO> getPagedApacheIIResult(String startTime, String endTime, int page, int size) {
        Page<BCarePgVteResultVO> pagination = new Page<>(page, size);
        List<BCarePgVteResultVO> results = bCarePgVteMapper.secletApacheIIPage(pagination, startTime, endTime);
        pagination.setRecords(results);
        return pagination;
    }
}


